<!--
 * @Date: 2022-04-19 11:27:01
 * @Author: 陶子
 * @LastEditTime: 2022-08-02 17:36:56
 * @FilePath: \jk_one-stop_cloud_mobile_v1.0\src\views\qualityManagement\qualityTask\qualityBatchReport.vue
 * @pageName: 这是--(质检任务——批量报工)--页面
-->
<template>
  <div>
    <Navbar :appTitle="appTitle" />
    <div class="search-content wrap-apply" :style="{top: GLOBAL.currentEnvironment ? '0' : '',height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 1.12rem)',paddingBottom: GLOBAL.currentEnvironment ? '0.66rem' : ''}">
      <div class="reportBox" v-for="(item,index) in totalData" :key="index">
        <van-cell-group style='margin-top:0.1rem'>
          <p class="label otherText">报工任务({{index+1}})</p>
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label  FormTit"><span></span>工单编号</p>
          <van-field v-model="item.orderCode" disabled placeholder="请输入" />
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label  FormTit"><span></span>工序</p>
          <van-field v-model="item.showProcessName" disabled placeholder="请输入" />
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label FormTit"><span></span>生产物料</p>
          <van-field disabled v-model="item.showProductName" placeholder="请先选择工单编号" />
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label required FormTit"><span></span>操作人</p>
          <!-- <van-field-select-picker label="" placeholder="请选择" v-model="item.operatorId" :columns="item.operatorList" :option="{ label: 'text', value: 'value' }"
            @confirm="peopleConfirm" @prePopShow="showPeopleDialog" /> -->
            <van-field-checkbox
              :supportClear="true"
              placeholder="请选择"
              v-model="item.operatorId"
              :columns="item.operatorList"
              :option="{ label: 'text', value: 'value' }"
            />
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label FormTit"><span></span>合格数</p>
          <div class="haveUnitBox">
            <van-field v-model="item.qualifiedNum" @input='formatInput("qualifiedNum",item.qualifiedNum,item)' @blur='checkValue("qualifiedNum",item.qualifiedNum,item)'
              placeholder="请输入" />
            <span>{{item.reportWorkUnitText}}</span>
          </div>
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label FormTit"><span></span>不合格数</p>
          <div class="haveUnitBox">
            <van-field v-model="item.notQualifiedNum" readonly @click="showUp(index)" placeholder="请输入" />
            <!-- <van-field v-model="item.notQualifiedNum" placeholder="请输入" @blur='checkValue("notQualifiedNum",item.notQualifiedNum,item)'
              @input='formatInput("notQualifiedNum",item.notQualifiedNum,item)' /> -->
            <span>{{item.reportWorkUnitText}}</span>
          </div>
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label  FormTit"><span></span>不合格原因</p>
          <van-field v-model="item.notQualifiedReasonText" readonly placeholder="请输入不合格数" />
          <!-- <van-field-checkbox label="" placeholder="请选择" v-model="item.notQualifiedReason" :columns="dictOptions" :option="{ label: 'text', value: 'value' }"
            @confirm="resonConfirm" /> -->
        </van-cell-group>
        <div class="search-bottom">
      <span class="btnconfirm" @click="btnConfirm">提交</span>
    </div>
      </div>
      <div style="margin-top: 0.12rem">
        <Examine @submitProcess="submitProcess" @getUserState="getUserState" type="0" :key="examKey" id="MESS_TASK_REPORT_WORK_APPLY_FOR_QUALITY" ref="examine" />
        <div style="height: 0.26rem"></div>
      </div>
      <not-qualified-num ref="NotQualifiedNum" :dataSource="dictOptions" @comfirm="comfirmReason"></not-qualified-num>
    </div>
  </div>
</template>
<script>
import { ajaxGetDictItems } from "@/api/api";
import Navbar from "@/components/navBar/navBar_right";
import ContactPickers from "@/components/choiceuse/ContactPickers";

import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import VanFieldCheckbox from "@/components/ActionSheet/VanFieldCheckbox";
import { clearNoNum, accAdd, accSub, setTitle } from "@/utils/util";
import Examine from "@/components/examine";
import { getReportTeamUserListByTaskId, reportBatchAdd } from "@/api/mobile";
import NotQualifiedNum from "@/components/choiceuse/NotQualifiedNum";
export default {
  name: "search",
  components: {
    ContactPickers,
    VanFieldSelectPicker,
    VanFieldCheckbox,
    Navbar,
    Examine,
    NotQualifiedNum
  },
  data() {
    return {
      totalData: [], //所有的数据
      dictOptions: [], //不合格原因
      examKey: 1,
      currentLoginUser: {},
      showPeopleSlect: false,
      currentIndex: 0,
      appTitle: this.$route.meta.title,
      appTitleText: this.$route.meta.title
    };
  },
  computed: {},
  beforeRouteLeave(to, from, next) {
    if (this.showPeopleSlect) {
      this.$refs.examine.closePicker();
      next(false);
    } if (this.$refs.NotQualifiedNum.show) {
      // this.appTitle = this.$route.meta.title
      this.upDateTitle(this.$route.meta.title)
      this.$refs.NotQualifiedNum.show = false
      next(false);
    } else {
      next();
    }
  },
  created() {
    this.currentLoginUser = JSON.parse(
      localStorage.getItem("pro__Login_Userinfo")
    ).value;
    ajaxGetDictItems("mess_not_qualified_reason", null).then((res) => {
      if (res.success) {
        this.dictOptions = res.result.map((item) => {
          let obj = {
            notQualifiedReasonText: item.text,
            notQualifiedReason: item.value,
            notQualifiedNum: ''
          }
          return obj
        })
      }
      this.getInitData();
    });
  },
  methods: {
    upDateTitle(v) {
      this.appTitle = v
      setTitle(this.appTitle)
    },
    comfirmReason(obj, arr) {
      // this.appTitle = this.$route.meta.title
      this.upDateTitle(this.$route.meta.title)
      let i = this.currentIndex
      this.totalData[i].notQualifiedReason = obj.notQualifiedReason
      this.totalData[i].notQualifiedReasonText = obj.notQualifiedReasonText
      this.totalData[i].notQualifiedNum = obj.notQualifiedNum
      this.totalData[i].dictOptions = arr
      this.checkValue("notQualifiedNum", obj.notQualifiedNum, this.totalData[i])
    },
    showUp(i) {
      // this.appTitle ='不合格数输入'
      this.upDateTitle('不合格数输入')
      this.currentIndex = i
      this.$refs.NotQualifiedNum.showUp(this.totalData[i].dictOptions)
    },
    getUserState(v) {
      this.showPeopleSlect = v;
    },
    //页面加载请求数据
    getInitData() {
      let rejectArr = JSON.parse(this.$route.params.selectArr);
      let selectArr = JSON.parse(JSON.stringify(rejectArr));
      this.totalData = [];
      for (let item of selectArr) {
        item.showProcessName = `${item.processCode}-${item.processName}`;
        item.showProductName = `${item.goodsCode}-${item.goodsName}`;
        item.qualifiedNum = item.availableNumForReport;
        item.notQualifiedNum = "";
        item.notQualifiedReason = '';
        let taskObj = {
          taskId: item.id,
        };
        getReportTeamUserListByTaskId(taskObj).then((res) => {
          if (res.success) {
            item.operatorList = res.result;
            for (let each of item.operatorList) {
              if (each.value == this.currentLoginUser.id) {
                item.operatorId = [each.value];
              }
            }
            item.dictOptions = this.dictOptions
            this.totalData.push(item);
          } else {
            this.$toast(res.message);
          }
        });
      }
    },
    resonConfirm(a) {},
    peopleConfirm(itemPeople) {},
    showPeopleDialog(callback) {},
    // 提交
    btnConfirm() {
      for (let i = 0; i < this.totalData.length; i++) {
        if (!this.totalData[i].operatorId || this.totalData[i].operatorId.length == 0) {
          this.$toast(`报工任务（${i + 1}）请选择操作人`);
          return;
        }
        if (
          !Number(this.totalData[i].notQualifiedNum) &&
          !Number(this.totalData[i].qualifiedNum)
        ) {
          this.$toast(`报工任务（${i + 1}）请输入合格数或不合格数`);
          return;
        }
        // if (
        //   this.totalData[i].notQualifiedNum > 0 &&
        //   this.totalData[i].notQualifiedReason.length == 0
        // ) {
        //   this.$toast(`报工任务（${i + 1}）不合格数大于0时，不合格原因必填`);
        //   return;
        // }
      }
      this.submitProcess();
    },
    submitProcess(e) {
      if (e && e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.handleSubmit(e);
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm();
      }
    },
    handleSubmit(processDataVo) {
      let dtoList = [];
      for (let item of this.totalData) {
        let obj = {
          notQualifiedNum: item.notQualifiedNum ? item.notQualifiedNum : "",
          notQualifiedReason: item.notQualifiedReason,
          operatorId: item.operatorId.join(','),
          orderId: item.orderId,
          qualifiedNum: item.qualifiedNum ? item.qualifiedNum : "",
          reportWorkNum: item.reportWorkNum ? item.reportWorkNum : "",
          taskId: item.id,
          type: "quality",
        };
        dtoList.push(obj);
      }
      console.log("我要准备提交了啊：", dtoList);
      let parameter = {
        dtoList: dtoList,
        processDataVo: processDataVo,
      };
      reportBatchAdd(parameter).then((res) => {
        if (res.success) {
          this.totalData = [];
          this.$router.go(-1);
          this.$toast("报工成功！");
        } else {
          this.$toast(res.message);
        }
      });
    },

    checkValue(type, value, item) {
      if (type == "qualifiedNum") {
        let num = accSub(
          Number(item.excessCanReportNum),
          Number(item.notQualifiedNum ? item.notQualifiedNum : 0)
        );
        if (Number(value) > Number(num)) {
          item[type] = "0";
          item.reportWorkNum = item.notQualifiedNum;
          this.$toast("报工总数不能大于最大应生产数！");
        } else {
          if (item.notQualifiedNum) {
            item.reportWorkNum = accAdd(
              Number(item.notQualifiedNum),
              Number(item.qualifiedNum)
            );
          } else {
            item.reportWorkNum = item.qualifiedNum;
          }
        }
      } else {
        let num = accSub(
          Number(item.excessCanReportNum),
          Number(item.qualifiedNum ? item.qualifiedNum : 0)
        );
        let qnum = accSub(
          Number(item.excessCanReportNum),
          Number(value)
        );
        if (Number(value) > Number(num)) {
          item.qualifiedNum = Number(qnum) > 0 ? qnum : 0
          item.reportWorkNum = accAdd(
            Number(value),
            Number(item.qualifiedNum)
          )
        } else {
          if (item.qualifiedNum) {
            item.reportWorkNum = accAdd(
              Number(item.notQualifiedNum),
              Number(item.qualifiedNum)
            );
          } else {
            item.reportWorkNum = item.notQualifiedNum;
          }
        }
      }
    },
    formatInput(type, value, item) {
      item[type] = clearNoNum(value);
      this.checkValue("qualifiedNum",item.qualifiedNum,item)
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
.search-content {
  //  padding-bottom: 0.5rem;
  position: fixed;
  top: 0.42rem;
  width: 100%;
  height: calc(100vh - 1rem);
  background: #f5f5f5;
  overflow: scroll;
  z-index: 99;
  .formgroup {
    background: #ffffff;
    // padding: 0 0.16rem;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
}
.bottomLine {
  height: 0.01rem;
  background-color: #f0f0f0;
  margin: 0 0.16rem;
}
.otherText {
  padding-bottom: 0.16rem;
  font-size: 0.16rem;
  font-weight: bold;
  color: #191f25;
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 0.16rem;
  /deep/ .van-cell {
    padding-right: 0;
    width: 2.6rem;
  }
  /deep/ .van-field__control {
    max-width: 3rem;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
.search-bottom {
  width: 100%;
  height: 0.5rem;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0px;
  padding: 0rem 0.11rem;
  box-sizing: border-box;
  font-size: 0.16rem;
  font-weight: 500;
  z-index: 999;
  .btnconfirm {
    width: 100%;
    height: 0.39rem;
    background: #1890ff;
    border-radius: 0.03rem;
    text-align: center;
    line-height: 0.39rem;
    font-size: 0.16rem;
    font-weight: 500;
    color: #ffffff;
  }
}
</style>
